package com.dataeco.api.controller;

import com.dataeco.api.dto.*;
import com.dataeco.api.dto.helper.BankAccountHelper;
import com.dataeco.api.dto.helper.UserHelper;
import com.dataeco.api.dto.helper.DataecoRoleHelper;
import com.dataeco.api.entity.*;
import com.dataeco.api.exception.*;
import com.dataeco.api.facility.PasswordService;
import com.dataeco.api.facility.Snowflake;
import com.dataeco.api.security.AuthenticationFacade;
import com.dataeco.api.service.*;
import com.dataeco.api.utils.ExceptionMsg;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/accounts")
public class UserController {

    private static final String DEFAULF_ROLE = "c92ffedcdd41000";
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private final AuthenticationFacade authenticationFacade;
    private final UserService userService;
    private final Snowflake snowflake;
    private final PasswordService passwordService;
    private final BankAccountService bankAccountService;
    private final EmailService emailService;
    private final DataecoUserRoleService dataecoUserRoleService;
    private final RedisService redisService;


    private final String SITUATIONOFREGISTER="register";
    private final String SITUATIONOFRESET="reset";

    @Autowired
    public UserController(AuthenticationFacade authenticationFacade, UserService userService,
                          Snowflake snowflake,
                          PasswordService passwordService, BankAccountService bankAccountService,
                          EmailService emailService, DataecoUserRoleService dataecoUserRoleService,
                           RedisService redisService) {
        this.authenticationFacade = authenticationFacade;
        this.userService = userService;
        this.snowflake = snowflake;
        this.passwordService = passwordService;
        this.bankAccountService = bankAccountService;
        this.emailService = emailService;
        this.dataecoUserRoleService = dataecoUserRoleService;
        this.redisService = redisService;
    }



    //get user roles
    @GetMapping("/currUser")
    public ResponseEntity getUser() {
        String email = authenticationFacade.getUserDetails().getUsername();
        User user = this.userService.findByEmail(email);
        if (Objects.isNull(user)) {
            throw new NotCurrUserException("The current user is not found");
        }
        List<UsersRoles> dataecoUserRoleList = this.dataecoUserRoleService.findByUserId(user.getId());
        List<Roles> dataecoRoleList = new ArrayList<>();
        List<DataecoRoleInfo> result = new ArrayList<>();
        for (UsersRoles dataecoUserRole : dataecoUserRoleList) {
            if (dataecoUserRoleList.size() == 0) {
                break;
            }
            if (Objects.isNull(dataecoUserRole)) {
                continue;
            }
            Roles dataecoRole = dataecoUserRole.getUserRoleKey().getDataecoRole();
            dataecoRoleList.add(dataecoRole);
        }
        result.addAll(dataecoRoleList.stream().map(new DataecoRoleHelper()::convertDataecoRoleToDataecoRoleInfo).collect(Collectors.toList()));
        User2Info userInfo = new User2Info();
        userInfo.setUsername(user.getEmail());
        userInfo.setUserRoles(result);
        return ResponseEntity.ok(userInfo);
    }
    //get user info
    @GetMapping("/me")
    public ResponseEntity me() {
        String email = authenticationFacade.getUserDetails().getUsername();
        User user = userService.findByEmail(email);
        return ResponseEntity.ok(convert(user));
    }

    @GetMapping("/getVerificationCode")
    public void getVerificationCode(@RequestParam("uniqueKey") String uniqueKey,
                                     HttpServletResponse response)
            throws ServletException, IOException {
        //设置Content-Type响应头
        response.setContentType("image/jpeg");
        //下面三条语句用于设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        OutputStream out = response.getOutputStream();
        int width = 106;
        int height = 36;

        //建立指定宽、高和BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        //随机生成类
        Random random = new Random();
        //生成背景色
        g.setColor(getRandColor(200,250));

        g.fillRect(0, 0, width, height);

        // 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
        g.setColor(getRandColor(160,200));
        for (int i=0;i<155;i++)
        {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x,y,x+xl,y+yl);
        }

        //设置字体
        g.setFont(new Font("Times New Roman",Font.ITALIC,18));
        String sRand = "";
        String []a = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
        String code="";
        for(int i = 0; i < 4 ; i++){
            String rand = a[random.nextInt(61)];
            code += rand;
            sRand += rand;
            g.setFont(new Font("宋体", Font.PLAIN, 18));
            //设置随机颜色
            g.setColor(new Color(20 + random.nextInt(110),20 + random.nextInt(110),20 + random.nextInt(110)));
            //绘制
            g.drawString(rand, 29*i + 6, 25);
        }

        g.dispose();
        //输出图像到页面
        ImageIO.write(image, "JPEG", out);
        out.close();
        redisService.set(uniqueKey,code);
    }
    @GetMapping("/verificationCode")
    public ResponseEntity verificationCode(@RequestParam("uniqueKey") String uniqueKey,
                                           @RequestParam("code") String code) {
        String resultCode = redisService.getStringByKey(uniqueKey);
        ResponseInfo responseInfo  = new ResponseInfo();
        if(!Objects.isNull(resultCode)){
            resultCode =  resultCode.toLowerCase();
            code = code.toLowerCase();
                if(resultCode.equals(code)){
                    responseInfo.setCode(1);
                    responseInfo.setMessage("verify successfully");//验证通过
                    return ResponseEntity.ok(responseInfo);
                }else{
                    responseInfo.setCode(2);
                    responseInfo.setMessage("verification code error");//验证码错误
                    return ResponseEntity.ok(responseInfo);
                }
        }else{
            responseInfo.setCode(0);
            responseInfo.setMessage("verification code invalid");//验证码失效
            return ResponseEntity.ok(responseInfo);
        }
    }

    //给定范围获得随机颜色
    private Color getRandColor(int fc,int bc){
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
    }



    @PostMapping("/signupNotInsert")
    public ResponseEntity registerNotInsertDB(@RequestBody UserInfo request) {
        if ((Objects.isNull(request.getEmail())) || ("".equalsIgnoreCase(request.getEmail()))){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("002");
            exceptionMsg.setMessage("Email is null or '' .");
            return ResponseEntity.ok(exceptionMsg);
        }
        String email = request.getEmail();
        User user=this.userService.findByEmail(email);
        if (!Objects.isNull(user)){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("005");
            exceptionMsg.setMessage("Existing email");
            return ResponseEntity.ok(exceptionMsg);
        }
        String regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
        if (!email.matches(regex)) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("001");
            exceptionMsg.setMessage("The style of Email is not correct");
            return ResponseEntity.ok(exceptionMsg);
        }
        if ((Objects.isNull(request.getQq())) || ("".equalsIgnoreCase(request.getQq()))){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("003");
            exceptionMsg.setMessage("qq is null or '' ");
            return ResponseEntity.ok(exceptionMsg);
        }
        this.redisService.setForUsers(email,request.getQq());
        this.emailService.notifyForNewUserPassword(email,request.getInternationalization(),request.getQq());
        ExceptionMsg exceptionMsg=new ExceptionMsg();
        exceptionMsg.setCode("004");
        exceptionMsg.setMessage("Succeed");
        return ResponseEntity.ok(exceptionMsg);

    }

    @PostMapping("/isExisting")
    public ResponseEntity registerInsertRedis(@RequestBody UserInfo request) {
        if ((Objects.isNull(request.getEmail())) || ("".equalsIgnoreCase(request.getEmail()))){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("000");
            exceptionMsg.setMessage("Email is null or '' .");
            return ResponseEntity.ok(exceptionMsg);
        }
        if ((Objects.isNull(request.getQq())) || ("".equalsIgnoreCase(request.getQq()))){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("001");
            exceptionMsg.setMessage("qq is null or ''");
            return ResponseEntity.ok(exceptionMsg);
        }
        String email = request.getEmail();
        String qq=this.redisService.getStringByKey(email);

        if (Objects.isNull(qq)){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("004");
            exceptionMsg.setMessage("There is no such the email.");
            return ResponseEntity.ok(exceptionMsg);
        }
        if (!request.getQq().equalsIgnoreCase(qq)){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("002");
            exceptionMsg.setMessage("There is  the email but no such the qq.");
            return ResponseEntity.ok(exceptionMsg);
        }

        User user=this.userService.findByEmail(email);
        if (!Objects.isNull(user)){
            if (!Objects.isNull(user.getPassword())){
                ExceptionMsg exceptionMsg=new ExceptionMsg();
                exceptionMsg.setCode("005");
                exceptionMsg.setMessage("This is clicking again.");
                return ResponseEntity.ok(exceptionMsg);
            }
        }
        ExceptionMsg exceptionMsg=new ExceptionMsg();
        exceptionMsg.setCode("003");
        exceptionMsg.setMessage("Succeed");
        return ResponseEntity.ok(exceptionMsg);

    }

    @PostMapping("/emailAgain")
    public ResponseEntity sendEmailAgain(@RequestBody UserBasicInfo request) {
        if ((Objects.isNull(request.getEmail())) || ("".equalsIgnoreCase(request.getEmail()))){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("002");
            exceptionMsg.setMessage("Email is null or '' .");
            return ResponseEntity.ok(exceptionMsg);
        }
        String qq="";
        if (SITUATIONOFRESET.equalsIgnoreCase(request.getSituation())){
            User user=this.userService.findByEmail(request.getEmail());
            qq=user.getQq();
        }
        String email = request.getEmail();
        String regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
        if (!email.matches(regex)) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("001");
            exceptionMsg.setMessage("The style of Email is not correct");
            return ResponseEntity.ok(exceptionMsg);
        }
        String situation=request.getSituation();
        if (SITUATIONOFREGISTER.equalsIgnoreCase(situation)){
            this.emailService.notifyForNewUserPassword(email,request.getInternationalization(),request.getQq());
        }
        if (SITUATIONOFRESET.equalsIgnoreCase(situation)){
            this.emailService.notifyForResetPassword(email,request.getInternationalization());
        }
        ExceptionMsg exceptionMsg=new ExceptionMsg();
        exceptionMsg.setCode("004");
        exceptionMsg.setMessage("Succeed");
        return ResponseEntity.ok(exceptionMsg);

    }

    @PostMapping("/signupOfficial")
    public ResponseEntity registerOfficial(@RequestBody UserInfo request) {
        User oldUser = userService.findByEmail(request.getEmail());
        if (!Objects.isNull(oldUser)) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("000");
            exceptionMsg.setMessage("Existing email");
            return ResponseEntity.ok(exceptionMsg);
        }
        String email = request.getEmail();
        if ((Objects.isNull(request.getEmail())) || ("".equalsIgnoreCase(request.getEmail()))){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("002");
            exceptionMsg.setMessage("Email is null or '' .");
            return ResponseEntity.ok(exceptionMsg);
        }
        if ((Objects.isNull(request.getQq())) || ("".equalsIgnoreCase(request.getQq()))){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("003");
            exceptionMsg.setMessage("qq is null or '' ");
            return ResponseEntity.ok(exceptionMsg);
        }
        String regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
        if (!email.matches(regex)) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("001");
            exceptionMsg.setMessage("The style of Email is not correct");
            return ResponseEntity.ok(exceptionMsg);
        }
        String password = request.getPassword();
        if (password.length() < 6 || password.length() > 256) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("005");
            exceptionMsg.setMessage("Password`s length is not in the range of 6 to 256");
            return ResponseEntity.ok(exceptionMsg);
        }
        String ackPassword = request.getAckPassword();
        if (!(password.equals(ackPassword))) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("006");
            exceptionMsg.setMessage("Password and ackPassword are not the same!");
            return ResponseEntity.ok(exceptionMsg);
        }
        User user = new UserHelper().convertUserInfoToUserEntity(request);
        user.setId(snowflake.nextHexString());
        String salt = passwordService.makeSalt();
        user.setSalt(salt);
        String credentials = passwordService.encryptPassword(user.getPassword(), salt);
        user.setCredentials(credentials);
        user.setAlg(passwordService.getAlgorithmName());
        user.setHashIterations(passwordService.getHashIterations());
        user.setLocked(Boolean.FALSE);
        user.setCreatedAt(new Date());
        user.setModifiedAt(new Date());
        this.emailService.notifyForNewUser(email);
        UsersRoles dataecoUserRole = this.dataecoUserRoleService.addUserRole(user.getId(), DEFAULF_ROLE);
        if (Objects.isNull(dataecoUserRole)) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("008");
            exceptionMsg.setMessage("Account creation failed for userId or roleId");
            return ResponseEntity.ok(exceptionMsg);
        }
        ExceptionMsg exceptionMsg=new ExceptionMsg();
        exceptionMsg.setCode("004");
        exceptionMsg.setMessage("Succeed");
        return ResponseEntity.ok(exceptionMsg);

    }
    @PostMapping("/retrievePw")
    public ResponseEntity retrievePw(@RequestBody UserBasicInfo userBasicInfo){
        User oldUser=this.userService.findByEmail(userBasicInfo.getEmail());
        if (Objects.isNull(oldUser)){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("000");
            exceptionMsg.setMessage("There is no such email in db.");
            return ResponseEntity.ok(exceptionMsg);
        }
        this.emailService.notifyForResetPassword(oldUser.getEmail(), userBasicInfo.getInternationalization());
        ExceptionMsg exceptionMsg=new ExceptionMsg();
        exceptionMsg.setCode("001");
        exceptionMsg.setMessage("Succeed");
        return ResponseEntity.ok(exceptionMsg);
    }

    @PostMapping("/resetPw")
    public ResponseEntity resetPw(@RequestBody UserInfo userInfo){
        User user = userService.findByEmail(userInfo.getEmail());
        if (Objects.isNull(user)) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("000");
            exceptionMsg.setMessage("can not find the user");
            return ResponseEntity.ok(exceptionMsg);
        }
        String password=userInfo.getPassword();
        if (password.length() < 6 || password.length() > 256) {
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("001");
            exceptionMsg.setMessage("NewPassword`s length is not in the range of 6 to 256");
            return ResponseEntity.ok(exceptionMsg);
        }

        if (!userInfo.getPassword().equalsIgnoreCase(userInfo.getAckPassword())){
            ExceptionMsg exceptionMsg=new ExceptionMsg();
            exceptionMsg.setCode("002");
            exceptionMsg.setMessage("The two times`s password is not same.");
            return ResponseEntity.ok(exceptionMsg);
        }

        String newSalt = passwordService.makeSalt();
        String newCredentials = passwordService.encryptPassword(password, newSalt);
        user.setPassword(password);
        user.setSalt(newSalt);
        user.setCredentials(newCredentials);
        user.setAlg(passwordService.getAlgorithmName());
        user.setHashIterations(passwordService.getHashIterations());
        user.setModifiedAt(new Date());
        userService.saveUser(user);
        ExceptionMsg exceptionMsg=new ExceptionMsg();
        exceptionMsg.setCode("003");
        exceptionMsg.setMessage("Succeed");
        return ResponseEntity.ok(exceptionMsg);
    }


    @PutMapping("/password/update")
    public ResponseEntity updatePassword(@RequestBody UpdatePasswordRequest request) {
        User user = userService.findOne();
        if (Objects.isNull(user)) {
            throw new UnknownResourceException("can not find the user");
        }
        String encrytedPassword = passwordService.encryptPassword(request.getOldPassword(), user.getSalt());
        Map<String, String> result = new HashMap<>();
        if (!encrytedPassword.equals(user.getCredentials())) {
            result.put("fail", "false");//旧密码输入错误
            return ResponseEntity.ok(result);
        }
        String newPassword = request.getNewPassword();
        if (newPassword.length() < 6 || newPassword.length() > 256) {
            throw new PasswordFalseException("NewPassword`s length is not in the range of 6 to 256");
        }
        String newSalt = passwordService.makeSalt();
        String newCredentials = passwordService.encryptPassword(newPassword, newSalt);
        user.setPassword(newPassword);
        user.setSalt(newSalt);
        user.setCredentials(newCredentials);
        user.setAlg(passwordService.getAlgorithmName());
        user.setHashIterations(passwordService.getHashIterations());
        user.setModifiedAt(new Date());
        userService.saveUser(user);
        result.put("succeed", "true");
        return ResponseEntity.ok(result);
    }

    @GetMapping("/profile/basic")
    public ResponseEntity getBasicProfile() {
        User user = userService.findOne();
        if (Objects.isNull(user)) {
            throw new UnknownResourceException("can not find the user");
        }
        return ResponseEntity.ok(new UserHelper().convertUserEntityToUserInfo(user));
    }

    @PutMapping("/profile/basic/update")
    public ResponseEntity updateBasicProfile(@RequestBody UserInfo request) {
        User user = userService.findOne();
        if (Objects.isNull(user)) {
            throw new UnknownResourceException("cannot find the user");
        }
        if (!("".equals(request.getUsername())) && !(null == request.getUsername())) {
            user.setUsername(request.getUsername());
        }
        user.setCompany(request.getCompany());
        if (!("".equals(request.getEmail())) && !(null == request.getEmail())) {
            user.setEmail(request.getEmail());
        }
        user.setContact(request.getContact());
        user.setTelephone(request.getTelephone());
        user.setQq(request.getQq());
        user.setWebsite(request.getWebsite());
        userService.saveUser(user);
        return ResponseEntity.ok(new UserHelper().convertUserEntityToUserInfo(user));
    }

    @GetMapping("/profile/bank_account")
    public ResponseEntity getBankAccountInfo() {
        List<BankAccount> bankAccountList = bankAccountService.findAll();
        if (CollectionUtils.isEmpty(bankAccountList)) {
            List<BankAccount> bankAccountList1 = new ArrayList<>();
            BankAccount bankAccount = new BankAccount();
            bankAccount.setId(snowflake.nextHexString());
            bankAccount.setUser(userService.getUser());
            bankAccount.setCountry("");
            bankAccount.setBankName("");
            bankAccount.setLocation("");
            bankAccount.setPostcode("");
            bankAccount.setAccountName("");
            bankAccount.setCompanyAddress("");
            bankAccount.setAccountNumber("");
            bankAccount.setBankcode("");
            bankAccount.setCodeType(null);
            bankAccount.setCurrency("");
            bankAccountList1.add(bankAccount);
            bankAccountService.saveBankAccount(bankAccount);
            return ResponseEntity.ok(new Bank_accountAndLength(new BankAccountHelper().convertBankAccountEntityToBankAccountInfo(bankAccountList1), 0));
        }
        bankAccountService.saveBankAccount(bankAccountList.get(0));
        return ResponseEntity.ok(new Bank_accountAndLength(new BankAccountHelper().convertBankAccountEntityToBankAccountInfo(bankAccountList), bankAccountList.size()));
    }

    @PutMapping("/profile/bank_account/update")
    public ResponseEntity updateBankAccountInfo(@RequestBody BankAccountInfo request) {
        List<BankAccount> bankAccountList = bankAccountService.findAll();
        if (CollectionUtils.isEmpty(bankAccountList)) {
            throw new UnknownResourceException("bankAccountList is null or empty.");
        }
        BankAccount target = bankAccountList.get(0);
        if (!("".equals(request.getCountry())) && !(null == request.getCountry())) {
            if (request.getCountry().length() < 1 || request.getCountry().length() > 64) {
                throw new CountryLengthException("Country`s length is not in the range of 1 to 64");
            }
            target.setCountry(request.getCountry());
        }
        if (!("".equals(request.getBankName())) && !(null == request.getBankName())) {
            if (request.getBankName().length() < 1 || request.getBankName().length() > 128) {
                throw new BankLengthException("BankName`s length is not in the range of 1 to 128");
            }
            target.setBankName(request.getBankName());
        }
        if (!("".equals(request.getBankLocation())) && !(null == request.getBankLocation())) {
            if (request.getBankLocation().length() < 1 || request.getBankLocation().length() > 128) {
                throw new LocationLengthException("BankLocation`s length is not in the range of 1 to 128");
            }
            target.setLocation(request.getBankLocation());
        }
        if (!("".equals(request.getPostcode())) && !(null == request.getPostcode())) {
            if (request.getPostcode().length() < 1 || request.getPostcode().length() > 32) {
                throw new PostCodeLengthException("PostCode`s length is not in the range of 1 to 32");
            }
            target.setPostcode(request.getPostcode());
        }
        if (!("".equals(request.getAccountName())) && !(null == request.getAccountName())) {
            if (request.getAccountName().length() < 1 || request.getAccountName().length() > 128) {
                throw new AccountNameLenthException("AccountName`s length is not in the range of 1 to 128");
            }
            target.setAccountName(request.getAccountName());
        }
        if (!("".equals(request.getCompanyAddress())) && !(null == request.getCompanyAddress())) {
            if (request.getCompanyAddress().length() < 1 || request.getCompanyAddress().length() > 255) {
                throw new CompanyLengthException("CompanyAddress`s length is not in the range of 1 to 255");
            }
            target.setCompanyAddress(request.getCompanyAddress());
        }
        if (!("".equals(request.getAccountNum())) && !(null == request.getAccountNum())) {
            if (request.getAccountNum().length() < 1 || request.getAccountNum().length() > 32) {
                throw new AccountNumberLenthException("AccountNumber`s length is not in the range of 1 to 32");
            }
            target.setAccountNumber(request.getAccountNum());
        }
        if (!("".equals(request.getBankcode())) && !(null == request.getBankcode())) {
            target.setBankcode(request.getBankcode());
        }
        if (!("".equals(request.getCodeType())) && !(null == request.getCodeType())) {
            target.setCodeType(request.getCodeType());
        }
        if (!("".equals(request.getCurrency())) && !(null == request.getCurrency())) {
            target.setCurrency(request.getCurrency());
        }
        BankAccount newTarget = bankAccountService.saveBankAccount(target);
        return ResponseEntity.ok(new BankAccountHelper().convertBankAccountEntityToBankAccountInfo1(newTarget));
    }


    private UserInfo convert(User user) {
        UserInfo info = new UserInfo();
        info.setId(user.getId());
        info.setEmail(user.getEmail());
        info.setCompany(user.getCompany());
        info.setContact(user.getContact());
        info.setQq(user.getQq());
        info.setTelephone(user.getTelephone());
        info.setWebsite(user.getWebsite());
        return info;
    }
}
